package com.yycx.module.weixin.provider.controller;

import com.yycx.module.weixin.provider.service.impl.WeiXinOpenService;
import me.chanjar.weixin.common.error.WxErrorException;
import me.chanjar.weixin.open.bean.result.WxOpenAuthorizerInfoResult;
import me.chanjar.weixin.open.bean.result.WxOpenQueryAuthResult;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @author <a href="https://github.com/007gzs">007</a>
 * 改造支持多个微信开放平台
 */

@Controller
@RequestMapping("/common/wxOpen")
public class WxOpenApiController {
	private final Logger logger = LoggerFactory.getLogger(getClass());
	@Autowired
	private WeiXinOpenService wxOpenService;

	@GetMapping("/auth/goto_auth_url_show")
	@ResponseBody
	public String gotoPreAuthUrlShow(String componentAppId) {
		return "<a href='goto_auth_url?componentAppId=" + componentAppId + "'>go</a>";
	}

	@GetMapping("/auth/goto_auth_url")
	public void gotoPreAuthUrl1(HttpServletRequest request, HttpServletResponse response, String componentAppId) {
		String host = request.getHeader("host");
		String url = "http://" + host + "/api/common/myWxOpen/auth/jump?componentAppId=" + componentAppId;
		try {
			wxOpenService.switchover(componentAppId);
			url = wxOpenService.getWxOpenComponentService().getPreAuthUrl(url);
			response.sendRedirect(url);
		} catch (WxErrorException | IOException e) {
			logger.error("gotoPreAuthUrl", e);
			throw new RuntimeException(e);
		}
	}

	@GetMapping("/auth/jump")
	@ResponseBody
	public WxOpenQueryAuthResult jump(@RequestParam("auth_code") String authorizationCode, String componentAppId) {
		try {
			wxOpenService.switchover(componentAppId);
			System.out.println("----------componentAppId:" + componentAppId);
			logger.info("componentAppId{}", componentAppId);
			WxOpenQueryAuthResult queryAuthResult = wxOpenService.getWxOpenComponentService().getQueryAuth(authorizationCode);
			logger.info("getQueryAuth", queryAuthResult);
			return queryAuthResult;
		} catch (WxErrorException e) {
			logger.error("gotoPreAuthUrl", e);
			throw new RuntimeException(e);
		}
	}

	@GetMapping("/get_authorizer_info")
	@ResponseBody
	public WxOpenAuthorizerInfoResult getAuthorizerInfo(@RequestParam String appId, String componentAppId) {
		try {
			wxOpenService.switchover(componentAppId);
			return wxOpenService.getWxOpenComponentService().getAuthorizerInfo(appId);
		} catch (WxErrorException e) {
			logger.error("getAuthorizerInfo", e);
			throw new RuntimeException(e);
		}
	}
}
